package net.lgpage.util;

import java.lang.Character.UnicodeBlock;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class FormatUtil {

	public static class EncodeFormatUtil {
		public static String gbk2utf8(String gbk) {
			String l_temp = GBK2Unicode(gbk);
			l_temp = unicodeToUtf8(l_temp);

			return l_temp;
		}

		public static String utf82gbk(String utf) {
			String l_temp = utf8ToUnicode(utf);
			l_temp = Unicode2GBK(l_temp);

			return l_temp;
		}

		public static final boolean isChinese(char c) {
			Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
			if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
					|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
					|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
					|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
					|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
					|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
				return true;
			}
			return false;
		}

		public static int chineseStrLength(String str) {
			int length = 0;
			for (int i = 0; i < str.length(); i++) {
				char c = str.charAt(i);
				if (isChinese(c)) {
					length += 2;
				} else {
					length++;
				}
			}
			return length;
		}

		/**
		 * 
		 * @param str
		 * @return String
		 */

		public static String GBK2Unicode(String str) {
			StringBuffer result = new StringBuffer();
			for (int i = 0; i < str.length(); i++) {
				char chr1 = (char) str.charAt(i);

				if (!isNeedConvert(chr1)) {
					result.append(chr1);
					continue;
				}

				result.append("\\u" + Integer.toHexString((int) chr1));
			}

			return result.toString();
		}

		/**
		 * 
		 * @param dataStr
		 * @return String
		 */

		public static String Unicode2GBK(String dataStr) {
			int index = 0;
			StringBuffer buffer = new StringBuffer();

			int li_len = dataStr.length();
			while (index < li_len) {
				if (index >= li_len - 1
						|| !"\\u".equals(dataStr.substring(index, index + 2))) {
					buffer.append(dataStr.charAt(index));
					index++;
					continue;
				}

				String charStr = "";
				charStr = dataStr.substring(index + 2, index + 6);

				char letter = (char) Integer.parseInt(charStr, 16);

				buffer.append(letter);
				index += 6;
			}

			return buffer.toString();
		}

		public static boolean isNeedConvert(char para) {
			return ((para & (0x00FF)) != para);
		}

		/**
		 * utf-8 转unicode
		 * 
		 * @param inStr
		 * @return String
		 */
		public static String utf8ToUnicode(String inStr) {
			char[] myBuffer = inStr.toCharArray();

			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < inStr.length(); i++) {
				UnicodeBlock ub = UnicodeBlock.of(myBuffer[i]);
				if (ub == UnicodeBlock.BASIC_LATIN) {
					sb.append(myBuffer[i]);
				} else if (ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
					int j = (int) myBuffer[i] - 65248;
					sb.append((char) j);
				} else {
					short s = (short) myBuffer[i];
					String hexS = Integer.toHexString(s);
					String unicode = "\\u" + hexS;
					sb.append(unicode.toLowerCase());
				}
			}
			return sb.toString();
		}

		/**
		 * 
		 * @param theString
		 * @return String
		 */
		public static String unicodeToUtf8(String theString) {
			char aChar;
			int len = theString.length();
			StringBuffer outBuffer = new StringBuffer(len);
			for (int x = 0; x < len;) {
				aChar = theString.charAt(x++);
				if (aChar == '\\') {
					aChar = theString.charAt(x++);
					if (aChar == 'u') {
						// Read the xxxx
						int value = 0;
						for (int i = 0; i < 4; i++) {
							aChar = theString.charAt(x++);
							switch (aChar) {
							case '0':
							case '1':
							case '2':
							case '3':
							case '4':
							case '5':
							case '6':
							case '7':
							case '8':
							case '9':
								value = (value << 4) + aChar - '0';
								break;
							case 'a':
							case 'b':
							case 'c':
							case 'd':
							case 'e':
							case 'f':
								value = (value << 4) + 10 + aChar - 'a';
								break;
							case 'A':
							case 'B':
							case 'C':
							case 'D':
							case 'E':
							case 'F':
								value = (value << 4) + 10 + aChar - 'A';
								break;
							default:
								throw new IllegalArgumentException(
										"Malformed   \\uxxxx   encoding.");
							}
						}
						outBuffer.append((char) value);
					} else {
						if (aChar == 't')
							aChar = '\t';
						else if (aChar == 'r')
							aChar = '\r';
						else if (aChar == 'n')
							aChar = '\n';
						else if (aChar == 'f')
							aChar = '\f';
						outBuffer.append(aChar);
					}
				} else
					outBuffer.append(aChar);
			}
			return outBuffer.toString();
		}

	}

	public static class NumberFormatUtil {

		public static DecimalFormat dformat = new DecimalFormat("##0.00##");

		public static String format00(Double d) {
			if (d == null) {
				return "0.00";
			} else {
				return dformat.format(d);
			}
		}

		public static String format0(Double d) {
			if (d == null) {
				return "0.0";
			} else {
				return dformat.format(d);
			}
		}

	}

	public static class DateFormatUtil {

		public static Calendar parseToYyMMddCal(Calendar cal) {
			Calendar re = Calendar.getInstance();
			re.setTime(parseToYyMMddDate(cal.getTime()));
			return re;
		}

		public static Date parseToYyMMddDate(Date date) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String ymd = format.format(date);
			try {
				return format.parse(ymd);
			} catch (ParseException e) {
				return date;
			}
		}

		public static String getWeekNameFromCalendar(Calendar cal) {
			int week = cal.get(Calendar.DAY_OF_WEEK);
			String weeks[] = {"日","一","二","三","四","五","六"};
			return weeks[week-1];
		}

		public static String getHHmm(String yyMMddHHmm) {
			if (yyMMddHHmm == null) {
				return "";
			}
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			try {
				Date fd = format.parse(yyMMddHHmm);
				return getHHmm(fd);
			} catch (ParseException e) {
				return "";
			}
		}
		public static Date parseFromYyMMddHHmm(String yyMMddHHmm){
			SimpleDateFormat f = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm");
			try {
				return f.parse(yyMMddHHmm);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return null;
		}
		public static Date parseFromYyMMdd(String yyMMddHHmm){
			SimpleDateFormat f = new SimpleDateFormat(
					"yyyy-MM-dd");
			try {
				return f.parse(yyMMddHHmm);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return null;
		}

		public static String getYyMMddHHmm(Date date) {
			return getFormatDateString(date, "yyyy-MM-dd HH:mm");
		}

		public static String getYyMMdd(Date date) {
			return getFormatDateString(date, "yyyy-MM-dd");
		}

		public static String getMMdd(Date date) {
			return getFormatDateString(date, "MM-dd");
		}

		public static String getHHmm(Date date) {
			return getFormatDateString(date, "HH:mm");
		}

		public static String getFormatDateString(Date date, String fs) {
			if (date == null) {
				return "";
			}
			SimpleDateFormat format = new SimpleDateFormat(fs);
			String str = format.format(date);
			return str;
		}

		public static long dayCompare(Calendar pre, Calendar next) {// ��
			long t1 = pre.getTimeInMillis();
			long t2 = next.getTimeInMillis();
			// ��������
			long days = (t2 - t1) / (24 * 60 * 60 * 1000);
			return days;
		}

		public static Date convertTimeStamp(String timestamp) {
			long l;
			try {
				l = Long.parseLong(timestamp);
			} catch (NumberFormatException e) {
				return null;
			}
			return new Date(l * 1000);
		}

		public static Date convertTimeStamp(long timestamp) {
			return new Date(timestamp * 1000);
		}

		public static long minuteDiv(String timestamp) {
			Date date = convertTimeStamp(timestamp);
			Date now = new Date(System.currentTimeMillis());
			long between = (now.getTime() - date.getTime()) / 1000;// 除以1000是为了转换成秒
			long minute = between % 3600 / 60;
			return minute;
		}

		public static String leftMMss(Date date) {
			if (date == null) {
				return "00:00";
			}
			long between = (date.getTime() - System.currentTimeMillis()) / 1000;// 除以1000是为了转换成秒
			if (between < 0) {
				return "00:00";
			}
			long minute = between % 3600 / 60;
			long second = between % 60;
			return String.format("%02d:%02d", minute, second);
		}

		// 微博型时间转换工具方法
		public static String dateToRelativeTime(Date date) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date now = new Date();
			long between = (now.getTime() - date.getTime()) / 1000;// 除以1000是为了转换成秒
			long day = between / (24 * 3600);
			long hour = between % (24 * 3600) / 3600;
			long minute = between % 3600 / 60;
			long second = between % 60;
			String timeStr;
			if (day > 0 && day <= 29) {
				timeStr = day + "天前";
			} else if (day > 29) {
				timeStr = df.format(date);
			} else {
				if (hour > 0) {
					timeStr = hour + "小时前";
				} else {
					if (minute > 0) {
						timeStr = minute + "分钟前";
					} else {
						if (second >= 0) {
							timeStr = second + "秒前";
						} else {
							timeStr = "未来";
						}
					}
				}
			}
			return timeStr;
		}
	}

	public static class StringFormatUtil {

		public static String getFirstUpString(String str) {
			str = (str.charAt(0) + "").toUpperCase() + str.substring(1);
			return str;
		}

		public static String getUpCharsToLow(String str) {
			StringBuilder sb = new StringBuilder();
			for (char c : str.toCharArray()) {
				if (Character.isUpperCase(c)) {
					sb.append(Character.toLowerCase(c));
				}
			}
			return sb.toString();
		}

	}

}
